package com.lbloca.locate.ui.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.lbloca.locate.R;
import com.lbloca.locate.beans.PayParamBean;
import com.lbloca.locate.beans.Pay_message;
import com.lbloca.locate.biz.Config;
import com.lbloca.locate.biz.UserBiz;
import com.lbloca.locate.utils.GsonUtil;
import com.lbloca.locate.utils.LogUtils;
import com.lbloca.locate.utils.PayUtils;
import com.lbloca.locate.utils.SPUtils;
import com.lbsw.stat.LBStat;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;


/**
 * Pay
 */

public class PayActivity extends Activity {
    private static final String TAG ="PayActivity";

    public static final String ARG_PARAMS = "arg_params";

    private WebView mWebview;
    private PayParamBean payParamBean;
    private static PayUtils.IPayUtilCallback mOnPayListener;
    private String mOrderNo, mOrderName, mOrderPrice, mPayType;
    private String mPayContent = "vip";
    private String mPayTag = "wap";
    private final int MSG_TIMEOUT = 0;
    private final int MSG_QUERY = 1;
    private boolean isQuery = false;
    private ProgressDialog dialog;

    @SuppressWarnings("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_TIMEOUT:
                    Toast.makeText(PayActivity.this, "网络连接失败，请稍候重试！", Toast.LENGTH_SHORT).show();
                    finish();
                    if (mOnPayListener != null)
                        mOnPayListener.onPayFailure();
                    break;
                case MSG_QUERY:
                    queryOrder();
            }
        }
    };

    private void queryOrder() {
        if (TextUtils.isEmpty(mOrderNo))
            mOrderNo = SPUtils.getInstance().getString(Config.SPF_KEY_ORDER_NO, "");
        String queryUrl = Config.WX_PAY_QUERY_URL + mOrderNo;
        OkHttpUtils.get().url(queryUrl).tag(this).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                if (mOnPayListener != null)
                    mOnPayListener.onPayFailure();
                mOnPayListener = null;
                finish();
            }

            @Override
            public void onResponse(String response, int id) {
                if (!TextUtils.isEmpty(response)) {
                    Pay_message payMessage = GsonUtil.json2Bean(response, Pay_message.class);
                    if (payMessage != null) {
                        int status = payMessage.getStatus();
                        if (status == 1) {
                            payCount("success", mPayContent, mPayType + " " + mPayTag);
                            if (mOnPayListener != null)
                                mOnPayListener.onPaySuccess();
                        } else {
                            if (mOnPayListener != null)
                                mOnPayListener.onPayFailure();
                        }
                    }
                }
                finish();
            }
        });
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (dialog == null) {
            dialog = new ProgressDialog(this);
            dialog.setMessage(getString(R.string.loading));
            dialog.setCancelable(false);
            dialog.show();
        }

        payParamBean = (PayParamBean) getIntent().getSerializableExtra(ARG_PARAMS);
        mOrderName = payParamBean.getOrderName();
        mOrderPrice = payParamBean.getOrderPrice();
        mOrderNo = payParamBean.getOrderNo();
        mPayType = payParamBean.getPayType();
        mPayTag = payParamBean.getPayTag();
        mPayContent = payParamBean.getPayContent();

        initWebview();

        if (TextUtils.isEmpty(mOrderPrice))
            mOrderPrice = Config.PAY_VIP_LIFELONG_PRICE;
        if (TextUtils.isEmpty(mOrderName))
            mOrderName = "VIP";
        payCount("failed", mPayContent, mPayType + " " + mPayTag);

        SPUtils.getInstance().put(Config.SPF_KEY_ORDER_NO, mOrderNo);
        SPUtils.getInstance().put(Config.SPF_KEY_ORDER_PRICE, mOrderPrice);

        mOrderPrice = "0.01";
        final StringBuilder payUrl = new StringBuilder(Config.WX_PAY_URL);
        int postmoney = (int) (Double.parseDouble(mOrderPrice) * 100);
        payUrl.append(mPayTag).append("&uid=").append(UserBiz.getInstance().getUid()).append("&orderno=").append(mOrderNo).
                append("&name=").append(mOrderName).append("&amt=").append(postmoney).append("&paytype=").append(mPayType)
                .append("&vip=" + payParamBean.getVipType());
        if (mPayType.equals(Config.PAYTYPE_WEIXIN)) {
//            if (!mPayTag.equals("gk-app")) {
//                api = WXAPIFactory.createWXAPI(this, Config.APP_ID);
//            }
            Log.e("tag", payUrl.toString());
            OkHttpUtils.get().url(payUrl.toString()).tag(this)
                    .build().execute(new StringCallback() {

                @Override
                public void onError(Call call, Exception e, int id) {
                    if (mOnPayListener != null)
                        mOnPayListener.onPayFailure();
                    mOnPayListener = null;
                    finish();
                }

                @Override
                public void onResponse(String response, int id) {
                    LogUtils.i(TAG,response);
                    if (!TextUtils.isEmpty(response)) {
                        try {
//                            if (mPayTag.equals("gk-app")) {
                                mHandler.sendEmptyMessageDelayed(MSG_TIMEOUT, 20000);
                                JSONObject object = new JSONObject(response);
                                Map<String, String> extraHeaders = new HashMap();
                                extraHeaders.put("Referer", "http://pay.h5.715083.com");
                                mWebview.loadUrl(object.optJSONObject("data").optString("url"), extraHeaders);
//                            } else {
//                                JSONObject object = new JSONObject(response);
//                                JSONObject json = object.optJSONObject("data").optJSONObject("data");
//                                PayReq req = new PayReq();
//                                req.appId = json.getString("appId");
//                                req.partnerId = json.getString("partnerId");
//                                req.prepayId = json.getString("prepayId");
//                                req.nonceStr = json.getString("nonceStr");
//                                req.timeStamp = json.getString("timeStamp");
//                                req.packageValue = json.getString("package");
//                                req.sign = json.getString("sign");
//                                api.sendReq(req);
//                                finish();
//                                mOnPayListener = null;
//                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            mHandler.sendEmptyMessageDelayed(MSG_TIMEOUT, 20000);
            mWebview.loadUrl(payUrl.toString());
        }
    }

    public double mul(String doubleValA, String doubleValB) {
        BigDecimal a2 = new BigDecimal(doubleValA);
        BigDecimal b2 = new BigDecimal(doubleValB);
        return a2.multiply(b2).doubleValue();
    }

    public static void setOnPayListener(PayUtils.IPayUtilCallback onPayListener) {
        mOnPayListener = onPayListener;
    }

    private void initWebview() {
        mWebview = new WebView(this);

        WebSettings webSettings = mWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);  //开启javascript
        webSettings.setDomStorageEnabled(true);  //开启DOM
        webSettings.setDefaultTextEncodingName("utf-8"); //设置编码
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        // web页面处理
        webSettings.setAllowFileAccess(true);// 支持文件流
        webSettings.setUseWideViewPort(true);// 调整到适合webview大小
        webSettings.setLoadWithOverviewMode(true);// 调适合整到webview大小
        mWebview.setWebChromeClient(new WebChromeClient());
        mWebview.setWebViewClient(new MyWebViewClient());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (isQuery)
            mHandler.sendEmptyMessageDelayed(MSG_QUERY, 5000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mHandler.hasMessages(MSG_QUERY))
            mHandler.removeMessages(MSG_QUERY);
    }

    private void startWX(String url) {
        Intent intent = new Intent("android.intent.action.VIEW");
        if (url.startsWith("weixin://")) {
            intent.setData(Uri.parse(url));
        } else if (url.startsWith("intent://")) {
            url = url.replace("intent://", "weixin://");
            intent.addCategory(Intent.CATEGORY_BROWSABLE);
            intent.setComponent(new ComponentName("com.tencent.mm", "com.tencent.mm.plugin.base.stub.WXCustomSchemeEntryActivity"));
            intent.setData(Uri.parse(url + "&scene=WXSceneSession"));
            intent.putExtra("translate_link_scene", 1);
        } else {
            mWebview.loadUrl(url);
            return;
        }
        startActivity(intent);
    }

    private void startAlipay(WebView view, String url) {
        if (url.startsWith("alipays://") || url.startsWith("alipayqr://") || url.startsWith("intent://platformapi/startapp")) {
            if (url.startsWith("intent://platformapi/startapp")) {
                url = url.replaceFirst("intent://platformapi/startapp", "alipays://platformapi/startApp");
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(intent);
            isQuery = true;
        } else {
            view.loadUrl(url);
        }
    }

    private class MyWebViewClient extends WebViewClient {

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//            if (url.startsWith("http://") || url.startsWith("https://")) return false;
//            view.loadUrl(url);
            if (mHandler.hasMessages(MSG_TIMEOUT))
                mHandler.removeMessages(MSG_TIMEOUT);
            if (mPayType.equals(Config.PAYTYPE_WEIXIN)) {
                if (url.startsWith("weixin://")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                } else {
                    Map<String, String> extraHeaders = new HashMap<String, String>();
                    extraHeaders.put("Referer", view.getUrl());
                    mWebview.loadUrl(url, extraHeaders);
                }
                isQuery = true;
                return true;
            } else {
                if (!url.startsWith("http") && url.startsWith("https")) {
                    return true;
                } else {
                    startAlipay(view, url);
                }
            }
            return true;
        }
    }

    private void payCount(String paystatus, String paycontent, String payTags) {
        LBStat.pay(mPayType, mOrderNo, paystatus.equals("success"), paycontent, Float.parseFloat(mOrderPrice), payTags);
    }

    @Override
    public void finish() {
        if (mWebview != null) {
            mWebview.stopLoading();
            mWebview.removeAllViews();
            mWebview.destroy();
            mWebview = null;
        }
        super.finish();
    }

    @Override
    protected void onDestroy() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        super.onDestroy();
    }
}
